package com.qiku.service.impl;

import com.alibaba.fastjson.JSON;
import com.qiku.dao.CollectDao;
import com.qiku.dao.ResourceDao;
import com.qiku.dao.impl.CollectDaoImpl;
import com.qiku.dao.impl.ResourceDaoImpl;
import com.qiku.pojo.Collect;
import com.qiku.pojo.Resource;
import com.qiku.service.CollectService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CollectServiceImpl implements CollectService {
    private CollectDao collectDao = new CollectDaoImpl();
    private ResourceDao resourceDao = new ResourceDaoImpl();


    @Override
    public List<Resource> findResourceListByUserId(int userId) {
//        根据用户id获取  收藏  对象集合
        List<Collect> collectByUserId = collectDao.findCollectByUserId(userId);
//        声明一个新的集合存放  根据收藏品id获取到的资源列表集合
        List<Resource> list = new ArrayList<>();
//        遍历  收藏  对象集合  根据资源id 获取资源对象集合 并将其添加到新集合里
        for (Collect c : collectByUserId) {
            Resource resourceById = resourceDao.findResourceById(c.getResource_id());
            list.add(resourceById);
        }
        return list;
    }

    @Override
    public String addCollect(Collect collect) {
        List<Resource> resourceList = findResourceListByUserId(collect.getUser_id());
        String resourceId = collect.getResource_id();
        Map<String, String> map = new HashMap<>();
        boolean b = false;
        int i;
        if (resourceList != null) {
            for (Resource r : resourceList) {
                String resource_id = r.getId();
                if (resourceId.equals(resource_id)) {
                    b = true;
                    break;
                }
            }
            if (b) {
                i = 0;
            } else {
                i = collectDao.addCollect(collect);
            }
        } else {
            i = collectDao.addCollect(collect);
        }
        if (i > 0) {
            map.put("addMsg", "收藏成功");
        } else {
            map.put("addMsg", "收藏失败 ,请检查该资源是否已收藏");
        }
        String msgJSON = JSON.toJSONString(map);
        return msgJSON;
    }

    @Override
    public String subCollect(int u_id,String r_id) {
        Integer id = collectDao.findCollectById(u_id, r_id);
        Map<String, String> map = new HashMap<>();
        boolean flag = false;
        //若该用户收藏的资源不为空  否则  该用户目前没有收藏资源
        if (id != null) {
            int i = collectDao.subCollect(id);
            if (i > 0) {
                map.put("subMsg", "取消收藏成功。");
            } else {
                map.put("subMsg", "取消错误");
            }
        } else {
            map.put("subMsg", "该用户目前未收藏该资源!");
        }
        String msgJSON = JSON.toJSONString(map);
        return msgJSON;
    }
}
